package com.example.service;

import com.example.base.exception.CustomException;
import com.example.entity.Params;
import com.example.entity.User;

import com.example.mapper.UserMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public PageInfo<User> findBySearch(Params params) {
        //开启分页查询
        PageHelper.startPage(params.getPageNum(), params.getPageSize());

        List<User> list = userMapper.findBySearch(params);
        return PageInfo.of(list);
    }


    public void add(User user) {
        //1.用户名一定要有，否则不允许添加(需要用户名登录)
        if (user.getName() == null || "".equals(user.getName())) {
            throw new CustomException("用户名不能为空");
        }
        //2.进行重复性判断，同一名字的管理员不允许重复添加
        User admin = userMapper.findByName(user.getName());
        if (admin != null) {
            throw new CustomException("该用户名已存在");
        }
        //初始化一个密码
        if (user.getPassword() == null) {
            user.setPassword("123456");
        }
        userMapper.add(user);
    }

    public User login(User user) {
        if (user.getName() == null || "".equals(user.getName())) {
            throw new CustomException("用户名不能为空");
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            throw new CustomException("密码不能为空");
        }
        User admin = userMapper.findByNameAndPassword(user.getName(), user.getPassword());
        if (admin == null) {
            throw new CustomException("用户名或密码错误");
        }
        return admin;
    }

    public void update(User user) {
        userMapper.update(user);
    }

    public void delete(Integer id) {

        userMapper.deleteById(id);
    }
}
